import Vue from 'vue'
import Vuex from 'vuex'

import { loginAPI } from '../api/login'

Vue.use(Vuex)

export default new Vuex.Store({
    // 开启严格模式 —— 一切数据 的修改 只能 通过 mutation 进行
    strict: true,
    state: {
        token: window.localStorage.getItem('token') || '',
        refreshToken: window.localStorage.getItem('refresh_token') || ''
    },
    mutations: {
        setToken(state, tokenStr) {
            state.token = tokenStr
            window.localStorage.setItem('token', tokenStr)
        },
        setRefreshToken(state, refreshTokenStr) {
            state.refreshToken = refreshTokenStr
            window.localStorage.setItem('refresh_token', refreshTokenStr)
        }
    },
    actions: {
        async asyncLoginAction(store, formLogin) {
            // 1. 发送登录请求
            const resp = await loginAPI(formLogin)
            const { token, refresh_token: refreshToken } = resp.data
                // 2. 提交到mutation - 同步token 和 refreshToken
            store.commit('setToken', token)
            store.commit('setRefreshToken', refreshToken)
        }
    },
    modules: {}
})